<?php
//注入函数, 显示模板前传入系统配置系统
function output_global_vars($controller) {
	global $app_config;
	global $spConfig;
	$controller->web_root = WEB_ROOT;
	$controller->url_root = URL_ROOT;
	$controller->app_config = $app_config;
	$controller->urlsep = $spConfig['ext']['spUrlRewrite']['sep'] ? $spConfig['ext']['spUrlRewrite']['sep'] : '&';
	$controller->urlconn = $spConfig['ext']['spUrlRewrite']['sep'] ? $spConfig['ext']['spUrlRewrite']['sep'] : '=';
	$controller->date_version = date("Ymd");
	$controller->sys_ishtml = $spConfig['html']['enabled'];
	$controller->sys_ishtml_zxadv = $spConfig['html']['enabled_zxadv'];
	$controller->sys_entrance = $spConfig['entrance']['enabled'] ? 1 : '';
	if($controller->sys_entrance){
		$controller->sys_entrance_line = $spConfig['entrance']['entrance_line'] ? 1 : '';
		$controller->sys_entrance_change = $spConfig['entrance']['entrance_change'] ? 1 : '';
		/*
		//二级域名转向
		if(strtolower($_SERVER['SERVER_NAME']) == "localhost"){
			if(!$_SESSION["sys_entrance"])
				$_SESSION["sys_entrance"] = spClass("entrance")->getDefaultMark();
		}elseif(preg_match('/^([a-z0-9]{1,}).)?' . strtolower($spConfig['ext']['entrance']['topDomain']) . '$/', strtolower($_SERVER['SERVER_NAME']), $prep_domain_array))
			$_SESSION["sys_entrance"] = spClass("entrance")->getByMark($prep_domain_array[1]);
		else
			$_SESSION["sys_entrance"] = spClass("entrance")->getDefaultMark();
		*/
		/*
		//参数转向
		if($ent = strtolower($controller->spArgs("ent")))
			$sys_entrance = spClass("entrance")->getByMark($ent);
		if(!$sys_entrance)
			$sys_entrance = spClass("entrance")->getDefaultMark();
		*/
		//$sys_entrance = defined("ENT_MARK") ? spClass("entrance")->getByMark(ENT_MARK) : spClass("entrance")->getDefaultMark();
		$sys_entrance = defined("ENT_MARK") ? spClass("entrance")->getByMark(ENT_MARK) : array();
		if($sys_entrance){
			$controller->sys_entid = intval($sys_entrance["id"]);
			$controller->sys_ent = $sys_entrance["mark"];
			$controller->ent_root = WEB_ROOT ."/". $sys_entrance["mark"];
			$controller->ent_root_path = WEB_ROOT ."/". ENT_MARK;
			$controller->ent_title = $sys_entrance["name"] . "房产_";
			$controller->sys_ent = $sys_entrance;
		}
	}
}

function get_temperature($code, $check){
	include(dirname(dirname(__FILE__)) . DS . "weather_config.php");
	$dom = new MyDOMDocument;
	$debug = 0;
	if(!$check || $debug || ($weather_config[$code] && ($weather_config[$code]["time"] > time() - 24 * 60 * 60)))
		return array("result"=>$weather_config[$code], "from"=>0);
	/*
	$dom->load("http://weather.yahooapis.com/forecastrss?w=$code&u=c");
	$arr=$dom->toArray();
	$arr[rss][channel][item][description] = strtolower(trim($arr[rss][channel][item][description]));
	if($arr[rss][channel][item][description] && preg_match('/( - ([a-z ]{1,}). high: ([0-9]{1,}) low: ([0-9]{1,}))/', strtolower($arr[rss][channel][item][description]), $temperature_match)){
		$line_array = explode("<br />", $arr[rss][channel][item][description]);
		$temperature["img"] = $line_array[0];
		$temperature["min"] = $temperature_match[4];
		$temperature["max"] = $temperature_match[3];
		$temperature["weather"] = $temperature_match[2];
		$temperature["time"] = time();
		set_tp_config($code, $temperature);
		return array("result"=>$temperature, "from"=>1);
	}
	*/
	if($temperature = get_tp_array($code)){
		set_tp_config($code, $temperature);
		return array("result"=>$temperature, "from"=>1);
	}else{
		return array("result"=>$weather_config[$code], "from"=>0);
	}
}

function set_tp_config($code, $temperature){
	include(dirname(dirname(__FILE__)) . DS . "weather_config.php");
	if(!$code || !$temperature)
		return false;
	$weather_config[$code] = $temperature;
	$str = "<?php\r\n\$weather_config = ".var_export($weather_config, true).';';
	$fp = fopen(dirname(dirname(__FILE__)) . DS . 'weather_config.php', 'w');
	if (!fputs($fp,$str)){
		throw new Exception("未知错误，更新失败");
	}
}

function set_tp_config_city($code, $temperature){
	include("weather_city_config.php");
	if(!$code || !$temperature)
		return false;
	$weather_city_config[$code] = $temperature;
	$str = "<?php\r\n\$weather_city_config = ".var_export($weather_city_config, true).';';
	$fp = fopen('weather_city_config.php', 'w');
	if (!fputs($fp,$str)){
		throw new Exception("未知错误，更新失败");
	}
}

function get_code_tp($code){
	$temperature = get_tp_array($code);
	return array("result"=>$temperature);
}

function get_temperature_city($code, $check){
	include(dirname(dirname(__FILE__)) . DS . "weather_city_config.php");
	$debug = 0;
	if(!$check || $debug || ($weather_city_config[$code] && isset($weather_city_config[$code]["weather"]) && ($weather_city_config[$code]["time"] > time() - 24 * 60 * 60))){
		return array("result"=>$weather_city_config[$code], "from"=>0);
	}
	$temperature = get_tp_array($code);
	if(isset($temperature["weather"])){
		set_tp_config_city($code, $temperature);
		return array("result"=>$temperature, "from"=>1);
	}else{
		return array("result"=>$weather_city_config[$code], "from"=>0);
	}
}

function get_tp_array($code){
	/*
	$dom = new MyDOMDocument;
	$dom->load("http://weather.yahooapis.com/forecastrss?w=$code&u=c");
	$arr=$dom->toArray();
	$arr[rss][channel][item][description] = strtolower(trim($arr[rss][channel][item][description]));
	if($arr[rss][channel][item][description] && preg_match('/( - ([a-z ]{1,}). high: ([-0-9]{1,}) low: ([-0-9]{1,}))/', strtolower($arr[rss][channel][item][description]), $temperature_match)){
		$line_array = explode("<br />", $arr[rss][channel][item][description]);
		$temperature["img"] = $line_array[0];
		$temperature["min"] = $temperature_match[4];
		$temperature["max"] = $temperature_match[3];
		$temperature["weather"] = $temperature_match[2];
		$temperature["time"] = time();
		set_tp_config_city($code, $temperature);
		return array("result"=>$temperature, "from"=>1);
	}else{
		return array("result"=>$weather_city_config[$code], "from"=>0);
	}
	*/
	/* //获取woeid接口：http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22Barrie%20CA%22&format=xml*/
	if($http_str = http_request("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D$code&format=json&diagnostics=true&callback=")){
		$json = json_decode($http_str);
		//print_r($json);
		$description = $json->query->results->channel->item->description;
		$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
		preg_match_all($pattern,$description,$match);
		$temperature["img"] = $match[0][0];
		$temperature["min"] = round((floatval($json->query->results->channel->item->forecast[0]->low) - 32) * 5 / 9);
		$temperature["max"] = round((floatval($json->query->results->channel->item->forecast[0]->high) - 32) * 5 / 9);
		$temperature["weather"] = $json->query->results->channel->item->forecast[0]->text;
		$temperature["time"] = time();
	}
	return $temperature;
}

function getExchangeRate($to_Currency){
	$amount = urlencode($amount);
	if($to_Currency = urlencode($to_Currency)){
		$url = "http://download.finance.yahoo.com/d/quotes.csv?s=CNY".$to_Currency."=X&f=sl1d1t1ba&e=.csv";
		$ch = curl_init();
		$timeout = 0;
		$rawdata = "";
		$to_exchange = $data = array();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$rawdata = curl_exec($ch);
		curl_close($ch);
		$data = explode(',', $rawdata);
		$to_exchange["exchange"] = $data[1];
		$to_exchange["time"] = time();
	}
	$exchange["exchange"] = $to_exchange["exchange"];
	$exchange["time"] = $to_exchange["time"];
	if(!$exchange["exchange"] || !$exchange["time"])
		return false;
	return $exchange;
}

function get_exchange_config(){
	
}

function http_request($url, $method = array(), $timeout=30, $header=array()){
	if (!function_exists('curl_init')) {
		throw new Exception('server not install curl');
	}
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, true);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
	if (!empty($header)) {
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	}
	if($method["post"] == 1){
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $method["postdata"]);
	}
	$data = curl_exec($ch);
	list($header, $data) = explode("\r\n\r\n", $data);
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	if ($http_code == 301 || $http_code == 302) {
		$matches = array();
		preg_match('/Location:(.*?)\n/', $header, $matches);
		$url = trim(array_pop($matches));
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, false);
		$data = curl_exec($ch);
	}
	if ($data == false) {
		curl_close($ch);
	}
	@curl_close($ch);
	return $data;
}

if (!function_exists('json_encode')) {
    function json_encode($data) {
        switch ($type = gettype($data)) {
            case 'NULL':
                return 'null';
            case 'boolean':
                return ($data ? 'true' : 'false');
            case 'integer':
            case 'double':
            case 'float':
                return $data;
            case 'string':
                return '"' . addslashes($data) . '"';
            case 'object':
                $data = get_object_vars($data);
            case 'array':
                $output_index_count = 0;
                $output_indexed = array();
                $output_associative = array();
                foreach ($data as $key => $value) {
                    $output_indexed[] = json_encode($value);
                    $output_associative[] = json_encode($key) . ':' . json_encode($value);
                    if ($output_index_count !== NULL && $output_index_count++ !== $key) {
                        $output_index_count = NULL;
                    }
                }
                if ($output_index_count !== NULL) {
                    return '[' . implode(',', $output_indexed) . ']';
                } else {
                    return '{' . implode(',', $output_associative) . '}';
                }
            default:
                return ''; // Not supported
        }
    }
}

// 处理被 magic quotes 自动转义过的数据
if (get_magic_quotes_gpc())
{
	$in = array(& $_GET, & $_POST, & $_COOKIE, & $_REQUEST);
	while (list ($k, $v) = each($in))
	{
		foreach ($v as $key => $val)
		{
			if (! is_array($val))
			{
				$in[$k][$key] = stripslashes($val);
				continue;
			}
			$in[] = & $in[$k][$key];
		}
	}
	unset($in);
}
?>